package com.ecity.view {
	import com.ecity.events.GameEvent;
	import com.ecity.events.GameState;
	import com.ecity.table.Desktop;
	import com.ecity.table.HitButton;
	import com.ecity.table.Player;
	import com.ecity.table.TableDisplayObject;
	import com.ecity.util.GameLoader;
	import com.ecity.util.GridEngine;
	import com.ecity.util.HashMap;
	import flash.events.NativeDragEvent;
	import flash.utils.clearTimeout;
	import flash.utils.setTimeout;
	import com.ecity.table.TouchHands;
	
	/**
	 * ...
	 * @author ss
	 */
	public class Viewer extends TableDisplayObject implements IViewer {
		private var _button:HitButton;
		private var _desktop:Desktop;
		private var _resReady:Boolean = false;//资源是否加载完毕； 
		private var _isStarted:Boolean = false;
		private var _gameTurn:int = 1;
		private var _playerMap:HashMap = new HashMap();
		
		private var _engine:GridEngine = new GridEngine();
		
		private var activeIndex:int = 0;
		private var startPlayerId:int = 0;
		
		private var position:Array = [[0, 100], [200, 0], [0, -150], [ -200, 0]]
		private var scorelist:Array = new Array();
		
		private var _turnIndex:int = 1;
		private var _oneCounter:int = 0;
		
		private var _chooseable:Boolean;
		
		private var hands:TouchHands;
		
		public function Viewer(){
			initResource();
			_button = new HitButton();
			_desktop = new Desktop();
			this.addChildAtTop(_button);
			this.addChildAtBottom(_desktop);
		}
		
		/**
		 * 加载游戏资源
		 */
		private function initResource():void {
			var assetLoder:GameLoader = new GameLoader();
			assetLoder.startLoad(onSourceHandler);
		}
		/**
		 * 加载资源情况下各种判断
		 */
		private function onSourceHandler():void {
			if (arguments[0] == GameLoader.INIT_UI) {
				_desktop.initChildren("desktop");
			}else if (arguments[0] == GameLoader.PROGRESS) {
			}else {
				_resReady = true;
				_desktop.addEventListener(GameEvent.BACKGROUND_INITED,requestHandler);
				_desktop.addEventListener(GameEvent.CARD_SENT,requestHandler);
				_button.initChildren("button");
				hands = new TouchHands();
				hands.addEventListener(GameEvent.REQ_UNCOVER, requestHandler);
				this.addChild(hands);
			}
		}
		
		/**
		 *（I） 从开始页面进入游戏页面，这一步能够做到让游戏开始
		 */
		public function startGame():void{
			_isStarted = true;
			_desktop.showBackground();
		}
		
		/**
		 *（I） 判断相应的按钮是否碰撞到系统发送来的坐标方块
		 * 
		 * @param	hx
		 * @param	hy
		 */
		public function hitTestCase(hx:int, hy:int):void {
			
			if (GameState.hitable) {
				hands.hitTest(hx, hy);
				switch(GameState.state) {
					case GameState.GAME_READY:
						if (_button.hitTest(hx, hy, "b_startGame")) {
							if (_gameTurn == 1) {
								initGame();
							}else {
								resetGame();
							}
						}
						break;
					case GameState.WAIT_CHOOSE:
						var qk:int = _engine.hitTestZone(hx,hy,GridEngine["b4p"+activeIndex % 4])
						if (qk == 1) {
							choseButton(true);
						}else if (qk == -1) {
							choseButton(false);
						}
						break;
				}
			}
		}
		
		//=======================================================
		
		private function requestHandler(e:GameEvent):void {
			switch(e.type) {
				case GameEvent.BACKGROUND_INITED:
					setGameState("b_startGame", GameState.GAME_READY);
					break;
				case GameEvent.CARD_SENT:
					var p:Player = _playerMap.get("p" + e._info.index);
					p.reciveCard(e._info.value);
					if (_turnIndex == 1) {
						this.sendCard();
					}
					p.showHand(false);
					break;
				case GameEvent.WANTED_CARD:
					sendCard();
					break;
				case GameEvent.TOTHENEXT:
					var sc:Array = new Array();
					sc[0] = int(e._info.index);
					sc[1] = int(e._info.score);
					
					scorelist.push(sc);
					sendCard(true);
					break;
				case GameEvent.PUNISHED:
					var ranking:int = e._info.ranking;
					if (ranking == 3) {
						trace("hahahaha reset game=====>");
						resetGame();
					}else {
						showRanking(ranking+1);
					}
					break;
					
				case GameEvent.REQ_UNCOVER:
					var i :int = e._info.index;
					var player:Player = _playerMap.get("p" + i);
					player.showHand(true);
					break;
			}
		}
		
		private function setGameState(btnKey:String,state:String):void {
			_button.addButton(btnKey);
			_chooseable = true;
			GameState.state = state;
			GameState.hitable = true;
		}
		/**
		 * 初始化游戏
		 */
		private function initGame():void {
			initPlayer();
			this.sendCard();
		}

		/**
		 * 重置游戏
		 */
		private function resetGame():void {
			activeIndex = scorelist[0][0];
			startPlayerId = activeIndex;
			scorelist = new Array();
			for (var i:int = 0; i < 4; i++) {
				var p:Player = _playerMap.get("p" + i);
				p.reset();
			}
			setGameState("b_startGame", GameState.GAME_READY);
		}
		
		/**
		 * check the player score for win result
		 */
		private function checkWinner():void {
			for (var i:int = 0; i < 4; i++) {
				var p:Player = _playerMap.get("p" + i);
				p.showScore();
			}
			showRanking(0);
		}
		
		private function showRanking(ranking:int):void {
			var index:int = scorelist[ranking][0];
			var p:Player = _playerMap.get("p" + index);
			p.showRanking(ranking);
		}
		
		/***************************************
		 * 
		 */
		private function sendCard(toNext:Boolean = false):void {
			if (_turnIndex == 1) {
				_desktop.send(activeIndex % 4);
				if (_oneCounter==3) {
					_turnIndex++;
					_oneCounter = 0;
					hands.show();
					addUserbutton((activeIndex+1)%4);
				}else {
					_oneCounter++;
				}
				activeIndex ++;
			}else if (toNext) {
				activeIndex ++;
				if(activeIndex%4==startPlayerId){// if all the players have done his chice//check who is the winner then set the startId to the player;
						scorelist.sort(sortRankingByScore)
						_turnIndex = 1;
						checkWinner();
				}else {
					addUserbutton(activeIndex%4);
				}
				
			}else if(!toNext){
				_desktop.send(activeIndex % 4);
			}
			
		}
		
		private function sortRankingByScore(a:Array, b:Array):int {
			var sa:int = int(a[1]);
			var sb:int = int(b[1]);
			if(sa>sb){return -1}else if (sa<sb){return 1}else{return 0}
		}
		
		private function addUserbutton(index:int):void {
			var p:Player = _playerMap.get("p" + index);
			p.showChoseBtn();
			GameState.state = GameState.WAIT_CHOOSE;
		}
		
		private function choseButton(isWant:Boolean):void {
			var p:Player = _playerMap.get("p" + activeIndex % 4);
			p.choose(isWant);
		}
		
		private function initPlayer():void {
			for (var i:int = 0; i < 4; i++) {
				var p:Player = new Player(i);
				_playerMap.put("p" + i, p);
				p.addEventListener(GameEvent.WANTED_CARD, requestHandler);
				p.addEventListener(GameEvent.TOTHENEXT, requestHandler);
				p.addEventListener(GameEvent.PUNISHED, requestHandler);
				this.addChildAs(p);
			}
		}
		
		private function setPlayer(func:Function):void {
			_playerMap.eachValue(func);
		}
		
		
		
		
	}
}